const app = getApp()

Page({
  data: {
    addresses: [],
    selectedAddress: null,
    date: '',
    time: '',
    minDate: '',
    maxDate: '',
    selectedWastes: [],
    remark: '',
    totalPrice: 0
  },

  onLoad(options) {
    // 登录状态校验
    const token = wx.getStorageSync('access_token')
    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login?redirect=' + encodeURIComponent('/pages/create-order/create-order')
      })
      return
    }
    // 设置日期范围
    const now = new Date()
    const minDate = now.toISOString().split('T')[0]
    const maxDate = new Date(now.setDate(now.getDate() + 7)).toISOString().split('T')[0]
    
    this.setData({
      minDate,
      maxDate,
      date: minDate,
      time: '09:00'
    })

    this.loadAddresses()
  },

  loadAddresses() {
    const token = wx.getStorageSync('access_token')
    wx.request({
      url: `${app.globalData.baseUrl}/users/addresses/`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const addresses = res.data.results || res.data
          this.setData({ 
            addresses,
            selectedAddress: addresses.find(addr => addr.is_default) || addresses[0]
          })
        }
      }
    })
  },

  selectAddress(e) {
    const id = e.currentTarget.dataset.id
    const address = this.data.addresses.find(addr => addr.id === id)
    this.setData({ selectedAddress: address })
  },

  addAddress() {
    wx.navigateTo({
      url: '/pages/address/address'
    })
  },

  bindDateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },

  bindTimeChange(e) {
    this.setData({
      time: e.detail.value
    })
  },

  showWasteSelector() {
    wx.navigateTo({
      url: '/pages/waste-selector/waste-selector'
    })
  },

  // 接收废品选择页面返回的数据
  onWasteSelected(wastes) {
    const selectedWastes = wastes.map(waste => ({
      ...waste,
      amount: 1
    }))
    this.setData({
      selectedWastes,
    }, this.calculateTotal)
  },

  increaseAmount(e) {
    const id = e.currentTarget.dataset.id
    const wastes = this.data.selectedWastes.map(waste => {
      if (waste.id === id) {
        return { ...waste, amount: waste.amount + 1 }
      }
      return waste
    })
    this.setData({ selectedWastes: wastes }, this.calculateTotal)
  },

  decreaseAmount(e) {
    const id = e.currentTarget.dataset.id
    const wastes = this.data.selectedWastes.map(waste => {
      if (waste.id === id && waste.amount > 1) {
        return { ...waste, amount: waste.amount - 1 }
      }
      return waste
    })
    this.setData({ selectedWastes: wastes }, this.calculateTotal)
  },

  updateAmount(e) {
    const id = e.currentTarget.dataset.id
    const amount = parseInt(e.detail.value) || 1
    const wastes = this.data.selectedWastes.map(waste => {
      if (waste.id === id) {
        return { ...waste, amount }
      }
      return waste
    })
    this.setData({ selectedWastes: wastes }, this.calculateTotal)
  },

  calculateTotal() {
    const total = this.data.selectedWastes.reduce((sum, waste) => {
      return sum + waste.price * waste.amount
    }, 0)
    this.setData({ totalPrice: total.toFixed(2) })
  },

  submitOrder() {
    if (!this.data.selectedAddress) {
      wx.showToast({
        title: '请选择回收地址',
        icon: 'none'
      })
      return
    }

    if (this.data.selectedWastes.length === 0) {
      wx.showToast({
        title: '请选择回收废品',
        icon: 'none'
      })
      return
    }

    // 验证电话号码格式
    const phone = this.data.selectedAddress.phone
    if (!phone || !/^1\d{10}$/.test(phone)) {
      wx.showToast({
        title: '联系电话格式不正确',
        icon: 'none'
      })
      return
    }

    const token = wx.getStorageSync('access_token')
    
    // 格式化地址字符串
    const address = `${this.data.selectedAddress.province}${this.data.selectedAddress.city}${this.data.selectedAddress.district}${this.data.selectedAddress.address}`
    
    // 格式化预约时间为ISO格式
    const appointmentTime = new Date(`${this.data.date}T${this.data.time}:00`).toISOString()

    // 准备请求数据
    const requestData = {
      address: address,
      contact_name: this.data.selectedAddress.name,
      contact_phone: phone,
      appointment_time: appointmentTime,
      remark: this.data.remark || '',
      items_data: this.data.selectedWastes.map(waste => ({
        waste_type_id: parseInt(waste.id),
        weight: parseFloat(waste.amount),
        unit_price: parseFloat(waste.price)
      }))
    }

    // 打印请求数据以便调试
    console.log('订单提交数据:', requestData)

    wx.request({
      url: `${app.globalData.baseUrl}/orders/recycle-orders/`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: requestData,
      success: (res) => {
        console.log('服务器响应:', res)  // 添加服务器响应日志
        if (res.statusCode === 201) {
          wx.showToast({
            title: '订单提交成功',
            icon: 'success'
          })
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/order-detail/order-detail?id=' + res.data.id
            })
          }, 1500)
        } else {
          console.error('订单提交失败:', res)
          wx.showToast({
            title: res.data.detail || '订单提交失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('请求失败:', err)
        wx.showToast({
          title: '订单提交失败',
          icon: 'none'
        })
      }
    })
  }
})